const app = getApp()
import { list } from '../../../../api/goods'

Component({
  properties: {
    category_id: {
      type: Number,
      value: 0
    }
  },
  data: {
    loadmore: false,
    list: null,
    form: {
      page: 1,
      limit: 10,
      category: 0
    },
    abnor: {
      title: '抱歉！没找到相关商品~',
      button: ''
    }
  },
  ready () {
    wx.showLoading({ title: '加载中' })
    this.data.form.category = this.properties.category_id
    this.getList()
  },
  methods: {
    onReachBottom () {
      if (this.data.form.page == this.data.form.last_page) {
        this.setData({ loadmore: true })
      } else {
        this.data.form.page += 1
        this.getList()
      }
    },

    getList (res) {
      list(this.data.form).then(res => {
        const { data } = res
        this.data.list || (this.data.list = [])
        const list = this.data.list.concat(data.data)
        this.data.form.last_page = res.data.last_page
        this.setData({
          list: list,
          loadmore: data.last_page <= 1
        })
      })
        .finally(() => {
          wx.hideLoading()
        })
    },

    onChange (id) {
      const form = this.data.form
      form.page = 1
      form.category = id
      this.data.list = []
      this.setData({
        form: form
      })
      wx.showLoading({
        title: '加载中'
      })
      list(form).then(res => {
        this.getList(res)
      })
        .finally(() => {
          wx.hideLoading()
        })
    },

    redirect (event) {
      app.redirect(event.currentTarget.dataset.url)
    }
  }
})